<template>
  <div class="history-container">
    <div class="history-header">
      <h2>对话历史</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索对话内容..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          style="width: 300px; margin-right: 15px;"
        />
        <el-button type="danger" @click="clearAllHistory" :disabled="!hasHistory">
          <el-icon><Delete /></el-icon>
          清空历史
        </el-button>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="filters">
      <el-select v-model="selectedDateRange" placeholder="时间范围" @change="filterHistory">
        <el-option label="全部" value="all" />
        <el-option label="今天" value="today" />
        <el-option label="昨天" value="yesterday" />
        <el-option label="最近7天" value="week" />
        <el-option label="最近30天" value="month" />
      </el-select>
      
      <el-select v-model="selectedType" placeholder="对话类型" @change="filterHistory">
        <el-option label="全部" value="all" />
        <el-option label="普通对话" value="normal" />
        <el-option label="流式对话" value="stream" />
        <el-option label="工具调用" value="tool" />
      </el-select>
    </div>

    <!-- 对话历史列表 -->
    <div class="history-list" v-if="filteredHistory.length > 0">
      <div 
        v-for="conversation in filteredHistory" 
        :key="conversation.id"
        class="conversation-item"
        @click="openConversation(conversation)"
      >
        <div class="conversation-header">
          <div class="conversation-info">
            <h4>{{ conversation.title || '未命名对话' }}</h4>
            <div class="conversation-meta">
              <span class="time">{{ formatTime(conversation.timestamp) }}</span>
              <span class="type" :class="conversation.type">{{ getTypeLabel(conversation.type) }}</span>
              <span class="message-count">{{ conversation.messages.length }} 条消息</span>
            </div>
          </div>
          <div class="conversation-actions">
            <el-button type="text" @click.stop="deleteConversation(conversation.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
            <el-button type="text" @click.stop="exportConversation(conversation)">
              <el-icon><Download /></el-icon>
            </el-button>
          </div>
        </div>
        
        <div class="conversation-preview">
          <p>{{ getLastMessage(conversation) }}</p>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">💬</div>
      <h3>暂无对话历史</h3>
      <p>开始与AI对话，您的对话记录将显示在这里</p>
      <el-button type="primary" @click="$router.push('/')">
        开始对话
      </el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="filteredHistory.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="对话详情"
      width="80%"
      :before-close="handleClose"
    >
      <div class="conversation-detail" v-if="selectedConversation">
        <div class="detail-header">
          <h3>{{ selectedConversation.title || '未命名对话' }}</h3>
          <div class="detail-meta">
            <span>{{ formatTime(selectedConversation.timestamp) }}</span>
            <span :class="selectedConversation.type">{{ getTypeLabel(selectedConversation.type) }}</span>
          </div>
        </div>
        
        <div class="messages-container">
          <div 
            v-for="(message, index) in selectedConversation.messages" 
            :key="index"
            class="message-item"
            :class="message.role"
          >
            <div class="message-avatar">
              <el-icon v-if="message.role === 'user'"><User /></el-icon>
              <el-icon v-else><Robot /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-role">{{ message.role === 'user' ? '用户' : 'AI助手' }}</div>
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Message {
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
}

interface Conversation {
  id: string
  title?: string
  type: 'normal' | 'stream' | 'tool'
  messages: Message[]
  timestamp: Date
}

// 响应式数据
const searchQuery = ref('')
const selectedDateRange = ref('all')
const selectedType = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const dialogVisible = ref(false)
const selectedConversation = ref<Conversation | null>(null)

// 模拟历史数据
const conversationHistory = ref<Conversation[]>([
  {
    id: '1',
    title: 'Spring AI 框架讨论',
    type: 'normal',
    timestamp: new Date('2025-06-18T10:30:00'),
    messages: [
      {
        role: 'user',
        content: '请介绍一下Spring AI框架的主要特性',
        timestamp: new Date('2025-06-18T10:30:00')
      },
      {
        role: 'assistant',
        content: 'Spring AI是一个为AI工程应用提供的Spring框架。它提供了一个可移植的API，支持所有主要的模型提供者，使开发人员能够轻松地在不同的AI模型之间切换...',
        timestamp: new Date('2025-06-18T10:30:15')
      }
    ]
  },
  {
    id: '2',
    title: '文件操作工具使用',
    type: 'tool',
    timestamp: new Date('2025-06-18T09:15:00'),
    messages: [
      {
        role: 'user',
        content: '请帮我读取项目的所有Java文件',
        timestamp: new Date('2025-06-18T09:15:00')
      },
      {
        role: 'assistant',
        content: '我已经成功读取了项目中的Java文件。项目包含以下主要文件：AiMultiModelApplication.java、ChatClientConfig.java、ZhiPuAiController.java等...',
        timestamp: new Date('2025-06-18T09:15:30')
      }
    ]
  },
  {
    id: '3',
    title: '流式对话测试',
    type: 'stream',
    timestamp: new Date('2025-06-17T16:45:00'),
    messages: [
      {
        role: 'user',
        content: '请用流式方式介绍一下人工智能的发展历史',
        timestamp: new Date('2025-06-17T16:45:00')
      },
      {
        role: 'assistant',
        content: '人工智能的发展可以追溯到20世纪50年代。1950年，艾伦·图灵提出了著名的"图灵测试"...',
        timestamp: new Date('2025-06-17T16:45:10')
      }
    ]
  }
])

// 计算属性
const hasHistory = computed(() => conversationHistory.value.length > 0)

const filteredHistory = computed(() => {
  let filtered = [...conversationHistory.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    filtered = filtered.filter(conv => 
      conv.messages.some(msg => 
        msg.content.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    )
  }
  
  // 时间范围过滤
  if (selectedDateRange.value !== 'all') {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    
    filtered = filtered.filter(conv => {
      const convDate = new Date(conv.timestamp)
      
      switch (selectedDateRange.value) {
        case 'today':
          return convDate >= today
        case 'yesterday':
          const yesterday = new Date(today)
          yesterday.setDate(yesterday.getDate() - 1)
          return convDate >= yesterday && convDate < today
        case 'week':
          const weekAgo = new Date(today)
          weekAgo.setDate(weekAgo.getDate() - 7)
          return convDate >= weekAgo
        case 'month':
          const monthAgo = new Date(today)
          monthAgo.setMonth(monthAgo.getMonth() - 1)
          return convDate >= monthAgo
        default:
          return true
      }
    })
  }
  
  // 类型过滤
  if (selectedType.value !== 'all') {
    filtered = filtered.filter(conv => conv.type === selectedType.value)
  }
  
  return filtered
})

const totalItems = computed(() => filteredHistory.value.length)

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const filterHistory = () => {
  currentPage.value = 1
}

const openConversation = (conversation: Conversation) => {
  selectedConversation.value = conversation
  dialogVisible.value = true
}

const deleteConversation = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '确认删除', {
      type: 'warning'
    })
    
    const index = conversationHistory.value.findIndex(conv => conv.id === id)
    if (index > -1) {
      conversationHistory.value.splice(index, 1)
      ElMessage.success('对话已删除')
    }
  } catch {
    // 用户取消删除
  }
}

const clearAllHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有对话历史吗？此操作不可恢复！', '确认清空', {
      type: 'warning'
    })
    
    conversationHistory.value = []
    ElMessage.success('所有对话历史已清空')
  } catch {
    // 用户取消清空
  }
}

const exportConversation = (conversation: Conversation) => {
  const content = JSON.stringify(conversation, null, 2)
  const blob = new Blob([content], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `conversation_${conversation.id}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('对话已导出')
}

const getLastMessage = (conversation: Conversation) => {
  const lastMessage = conversation.messages[conversation.messages.length - 1]
  return lastMessage ? lastMessage.content.substring(0, 100) + '...' : ''
}

const getTypeLabel = (type: string) => {
  const labels = {
    normal: '普通对话',
    stream: '流式对话',
    tool: '工具调用'
  }
  return labels[type] || type
}

const formatTime = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const handleClose = () => {
  dialogVisible.value = false
  selectedConversation.value = null
}

onMounted(() => {
  console.log('History page loaded')
})
</script>

<style scoped>
.history-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.history-header h2 {
  font-size: 2.5rem;
  color: #333;
  font-weight: 700;
}

.header-actions {
  display: flex;
  align-items: center;
}

.filters {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
}

.filters .el-select {
  width: 150px;
}

.history-list {
  display: grid;
  gap: 15px;
  margin-bottom: 30px;
}

.conversation-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.conversation-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  border-color: #667eea;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.conversation-info h4 {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 8px;
}

.conversation-meta {
  display: flex;
  gap: 15px;
  align-items: center;
}

.conversation-meta span {
  font-size: 0.9rem;
  color: #666;
}

.type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.type.normal {
  background: #e3f2fd;
  color: #1976d2;
}

.type.stream {
  background: #f3e5f5;
  color: #7b1fa2;
}

.type.tool {
  background: #e8f5e8;
  color: #388e3c;
}

.conversation-actions {
  display: flex;
  gap: 5px;
}

.conversation-preview {
  color: #666;
  line-height: 1.5;
}

.conversation-preview p {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 10px;
}

.empty-state p {
  color: #666;
  margin-bottom: 25px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.conversation-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.detail-header h3 {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 10px;
}

.detail-meta {
  display: flex;
  gap: 15px;
  align-items: center;
}

.messages-container {
  display: grid;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border-radius: 10px;
}

.message-item.user {
  background: #f0f2ff;
}

.message-item.assistant {
  background: #f8f9fa;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
}

.message-role {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.message-text {
  color: #555;
  line-height: 1.6;
  margin-bottom: 8px;
}

.message-time {
  font-size: 0.85rem;
  color: #999;
}

@media (max-width: 768px) {
  .history-container {
    padding: 15px;
  }
  
  .history-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .filters {
    flex-direction: column;
  }
  
  .filters .el-select {
    width: 100%;
  }
  
  .conversation-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .conversation-meta {
    flex-wrap: wrap;
  }
}
</style>